//
//  IMCore.m
//  IMChezhil
//
//  Created by zhangliucheng on 15/7/1.
//  Copyright (c) 2015年 CheZhil. All rights reserved.
//

#import "IMCore.h"
#import "IMDefination.h"
#import "IMUserMessage.h"
#import "IMService.h"
#import "IMBlockQueue.h"
#import "IMLoginStateUtil.h"
#import "IMLoginReceiver.h"
#import "IMNotificationReceiver.h"
#import "IMMessageReceiver.h"
#import "IMMessageManager.h"

typedef enum {
    login_ing = 0,        // 正在连接
    login_success,
    login_fail
} LoginState;

@interface IMCore ()

@property (strong, nonatomic) IMService *service;
@property (strong, nonatomic) IMBlockQueue *queue;
@property (assign, nonatomic) LoginState loginState;

@end

@implementation IMCore

+ (instancetype)shareInstance {
    static IMCore *_sharedIMCore = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedIMCore = [IMCore new];
    });
    return _sharedIMCore;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.queue = [IMBlockQueue new];
        self.messageNotification = YES;     // 默认是开启推送消息
    }
    return self;
}

#pragma mark - 用户登录信息相关
- (void)loginWithUin:(NSString *)uin token:(NSString *)token clientId:(NSString *)cId {
    self.loginMessage = [[IMLoginMessage alloc] initWithUin:uin token:token clientId:cId];
    [IMLoginStateUtil saveLoginMessage:self.loginMessage];
}

- (void)logout {
    [self.service disConnectServer];
    [IMLoginStateUtil clearLoginMessage];
}

- (NSString *)getUin {
    return [IMLoginStateUtil getUin];
}

- (BOOL)haveLogined {
    if (NULL == [IMLoginStateUtil restoreLoginMessage]) {
        return NO;
    }
    return YES;
}

- (NSInteger)getMessageUnReadCount {
    return [[IMMessageManager shareInstance] getUnReadCount];
}

- (NSMutableArray *)getRecentLocalMessages:(NSInteger)count {
    return [[IMMessageManager shareInstance] getRecentMessages:count];
}

#pragma mark - 回调事件注册
- (void)registerNotificationReceiveDelegate:(id<IMNotificationReceiverDelegate>) receiveDelegate {
    [IMNotificationReceiver onRegisterNodification:receiveDelegate];
    self.service = [IMService new];
    [self.service connectServer];
}

- (void)registerMessageDelegate:(id<IMMessageReceiverDelegate>)messageDelegate {
    self.messageNotification = NO;          // 关闭消息推送
    [IMMessageReceiver registerMessageDelegate:messageDelegate];
}

- (void)removeMessageDelegate {
    self.messageNotification = YES;         // 打开消息推送
    [IMMessageReceiver removeMessageDelegate];
}

#pragma mark - 收发消息
- (IMMessage *)getSendMessage {
    // 如果正在登录并且队列里面第一个元素是登陆消息，直接发送出去
    if (self.loginState == login_ing) {
        if ([[self.queue peek] isKindOfClass:[IMLoginMessage class]]) {
            return [self.queue poll:2];
        } else {
            sleep(5);
            return nil;
        }
    }
    
    if (self.loginState == login_fail) {
        sleep(5);
        return [IMLoginStateUtil restoreLoginMessage];
    }
    return [self.queue poll:2];
}

- (void)sendInitMessage {
    [self.queue addFirst:[IMLoginStateUtil restoreLoginMessage]];
    
    self.loginState = login_ing;
    [IMLoginReceiver onRegisterNodification:^(BOOL success) {
        self.loginState = success ? login_success : login_fail;
    }];
}

- (IMTextMessage *)sendTextMessage:(NSString *)text {
    IMTextMessage *txtMsg = [[IMTextMessage alloc] initWithContent:text];
    [self.queue offer:txtMsg];
    return txtMsg;
}

- (IMUserMessage *)sendImageMessage:(NSString *)imagePath {
    return nil;
}

- (IMAudioMessage *)sendAudioMessage:(NSString *)audioPath {
    return nil;
}

@end